<template>
    <div class="background">
        <div class="loginCard">
            <el-form ref="form" size="large" autocomplete="off" v-if="!isRegister" :model="registerData" :rules="rules">
                <div class="centerTop">欢 迎 登 录</div>
                <el-form-item prop="username">
                    <el-input prefix-icon="User" placeholder="请输入账号" v-model="registerData.username" />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input prefix-icon="Lock" placeholder="请输入密码" type="password" show-password
                        v-model="registerData.password" @keyup.enter="login" />
                </el-form-item>
                <el-form-item>
                    <div class="flex-content">
                        <el-checkbox>记住我</el-checkbox>
                        <el-link type="primary" underline="never">忘记密码？</el-link>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button class="button" type="primary" auto-insert-space @click="login">
                        登录
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <el-link type="info" underline="never" @click="isRegister = true; clearRegisterData()">
                        注册 →
                    </el-link>
                </el-form-item>
            </el-form>
            <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
                <div class="centerTop">欢 迎 注 册</div>
                <el-form-item prop="username">
                    <el-input prefix-icon="User" placeholder="请输入账号" v-model="registerData.username" />
                </el-form-item>
                <el-form-item prop="password">
                    <el-input prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password" />
                </el-form-item>
                <el-form-item prop="confirmPassword">
                    <el-input prefix-icon="Lock" type="password" placeholder="请确认密码"
                        v-model="registerData.confirmPassword" />
                </el-form-item>
                <el-form-item>
                    <el-button class="button bgGreen" type="primary" auto-insert-space @click="register">
                        注册并登录
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <el-link type="info" underline="never" @click="isRegister = false; clearRegisterData()">
                        ← 返回
                    </el-link>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { userRegisterService, userLoginService, userInfoService } from "@/api/user";
import { ElMessage } from "element-plus";
import router from "@/router";
import { useTokenStore } from "@/store/token";
import { useUserStore } from "@/store/user"

const isRegister = ref(false)
const form = ref()
const tokenStore = useTokenStore()
const userStore = useUserStore()
const registerData = ref({
    username: 'admin',
    password: 'admin',
    confirmPassword: 'admin'
})
const validatePass = (rule, value, callback) => {
    if (value !== registerData.value.password) {
        callback(new Error("两次输入密码不一致！"))
    } else {
        callback()
    }
}
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 4, max: 16, message: '长度为4-16位非空字符', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 4, max: 16, message: '长度为4-16位非空字符', trigger: 'blur' },
    ],
    confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        { min: 4, max: 16, message: '长度为4-16位非空字符', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' }
    ],
}

const login = async () => {
    try {
        // 直接传递registerData不合适, registerData是一个响应式对象，如果需要取值，要用.value
        const data = await userLoginService(registerData.value);
        // 存储token
        // localStorage.setItem("token", data || {})
        // localStorage.removeItem('register_account')
        // 存储token到pinia
        tokenStore.setToken(data)
        ElMessage.success("登录成功")
        // 跳转到首页
        router.push('/')
    } catch { }
    finally {
        getUserInfo()
    }
}
const getUserInfo = async () => {
    const userinfo = await userInfoService();
    // 存储用户信息
    // 使用pinia存储用户信息
    userStore.setUser(userinfo)
}
const register = async () => {
    try {
        // 直接传递registerData不合适, registerData是一个响应式对象，如果需要取值，要用.value
        await userRegisterService(registerData.value);
        ElMessage.success("注册成功")
        setTimeout(() => {
            login()
        }, 1000)
    } catch { }
}

const clearRegisterData = () => {
    registerData.value = {
        username: '',
        password: '',
        confirmPassword: ''
    }
}

</script>

<style scoped>
.background {
    display: flex;
    justify-content: center;
    align-items: center;

    width: 100%;
    height: 100vh;
    background-image: url("@/assets/imgs/bg1.png");
    background-size: cover;
    overflow: hidden;
}

.loginCard {
    width: 400px;
    background-color: #fff;
    opacity: 0.85;
    border-radius: 5px;
    box-shadow: 0 5px rgba(0, 0, 0, 0.1);
    padding: 40px 20px 10px;
}

.el-form-item {
    margin-bottom: 15px;
}

.flex-content {
    display: flex;
    /* 启用 flex 布局 */
    justify-content: space-between;
    /* 关键：让子元素两端对齐 */
    align-items: center;
    /* 可选：垂直方向居中对齐（避免元素高度不同导致错位） */
    width: 100%;
    /* 确保容器宽度足够，否则 space-between 可能无效 */
}

.button {
    width: 100%;
}

.centerTop {
    text-align: center;
    margin-bottom: 30px;
    font-weight: bold;
    font-size: 24px;
}

.bgGreen {
    background-color: green;
}
</style>